import RNFS from 'react-native-fs';
import { unzip } from 'react-native-zip-archive';
import { Alert, NativeModules } from 'react-native';

const HotUpdateService = {
  bundleDir: `${RNFS.DocumentDirectoryPath}/bundles`,

  /**
   * 下载更新包（zip 格式）
   */
  async downloadUpdate(url) {
    try {
      const zipPath = `${RNFS.DocumentDirectoryPath}/update.zip`;
      const res = await RNFS.downloadFile({
        fromUrl: url,
        toFile: zipPath,
      }).promise;

      if (res.statusCode === 200) {
        console.log('✅ 下载完成:', zipPath);
        await this.unzipAndApply(zipPath);
      } else {
        throw new Error('下载失败: ' + res.statusCode);
      }
    } catch (e) {
      console.error('❌ 热更新下载错误:', e);
    }
  },

  /**
   * 解压并覆盖旧 JSBundle
   */
  async unzipAndApply(zipPath) {
    try {
      await RNFS.mkdir(this.bundleDir);
      await unzip(zipPath, this.bundleDir);
      console.log('✅ 解压完成:', this.bundleDir);
      Alert.alert('更新完成', '请重启应用以生效');
    } catch (e) {
      console.error('❌ 解压失败:', e);
    }
  },
};

export default HotUpdateService;
